package com.xfcy.blog.strategy.impl;

import com.xfcy.blog.entity.SystemConfig;
import com.xfcy.blog.service.SystemConfigService;
import com.xfcy.blog.strategy.FileUploadStrategy;
import com.xfcy.blog.utils.UUIDUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 晓风残月Lx
 * @date 2023/5/5 9:24
 */
@Service("localUploadStrategyImpl")
@RequiredArgsConstructor
public class LocalUploadStrategyImpl implements FileUploadStrategy {

    private final Logger logger = LoggerFactory.getLogger(AliUploadStrategyImpl.class);

    private final SystemConfigService systemConfigService;

    private String localFileUrl;

    @Value("${file.upload-folder}")
    private String UPLOAD_FOLDER;

    @PostConstruct
    private void init() {
        SystemConfig systemConfig = systemConfigService.getCustomizeOne();
        localFileUrl = systemConfig.getLocalFileUrl();
    }


    @Override
    public String fileUpload(MultipartFile file, String suffix) {
        String savePath = UPLOAD_FOLDER;
        String key = null;

        String fileName = UUIDUtils.getUuid() + "." + suffix;
        File dir = new File(savePath);
        // 判断当前目录是否存在
        if (!dir.exists()) {
            // 目录不存在，需要创建
            dir.mkdir();
        }
        try {
            // 将临时文件转存到指定位置
            file.transferTo(new File(savePath + fileName));
            key = localFileUrl + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return key;
    }


    @Override
    public boolean deleteFile(String ...fileNames) {
        String savePath = UPLOAD_FOLDER;
        for (String fileName : fileNames) {
            File file = new File(savePath + fileName);
            try {
                // 判断文件是否存在
                if (!file.exists()) {
                    // 文件不存在
                    logger.info("删除文件失败：{}", fileName);
                } else {
                    file.delete();  // 删除图片
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    @Override
    public List<String> getAllImages() {
        List<String> allImage = new ArrayList<>();
        String path = UPLOAD_FOLDER;
        File folder = new File(path);
        File[] files = folder.listFiles();
        for (File file : files) {
            System.out.println(file.getName());
            allImage.add(file.getName());
        }
        return allImage;
    }
}
